<template>
  <!-- 车间表单弹窗 -->
  <el-dialog
    :close-on-click-modal="false"
    v-model="visibleDialog"
    :title="props.title"
    width="600"
    draggable
    @close="closeDialog"
  >
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="80">
      <el-row>
        <el-col :span="12">
          <el-form-item label="车间编号" prop="shopFloorCode">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.shopFloorCode"
              placeholder="请输入车间编号"
              clearable
            />

            <span v-else>{{ formData.shopFloorCode }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="车间名称" prop="shopFloorName">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.shopFloorName"
              placeholder="请输入车间名称"
              clearable
            />

            <span v-else>{{ formData.shopFloorName }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="工厂" prop="plantId">
            <el-select
              v-if="!props.isReadonly"
              v-model="formData.plantId"
              placeholder="请输入工厂"
              clearable
              @change="changePlant"
              filterable
            >
              <el-option
                v-for="plant in plantList"
                :key="plant.id"
                :label="plant.organizationCode"
                :value="plant.id"
              />
            </el-select>
            <span v-else>{{ plantCode(formData.plantId) }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="是否启用" prop="enabled">
            <el-radio-group v-model="formData.enabled" v-if="!props.isReadonly">
              <el-radio :label="1">启用</el-radio>
              <el-radio :label="0">停用</el-radio>
            </el-radio-group>
            <span v-else>{{ formData.enabled == 1 ? "启用" : "停用" }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="备注" prop="remarks">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.remarks"
              type="textarea"
              placeholder="请输入备注"
              clearable
            />

            <span v-else>{{ formData.remarks }}</span>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button
          v-if="!props.isReadonly"
          type="primary"
          :loading="loading"
          @click="handleSubmit"
          >确 定</el-button
        >
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "MDMMDMSHOPFLOORADDORUPDATE",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    setTimeout(() => {
      formRef.value.clearValidate();
    }, 50);
  }
);

const rules = reactive({
  plantId: [
    { required: true, message: "请选择工厂", trigger: "change" },
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  shopFloorCode: [
    { required: true, message: "请输入车间编号", trigger: "blur" },
    { min: 1, max: 20, message: "长度在 1 到 20 个字符", trigger: "blur" },
  ],
  shopFloorName: [
    { required: true, message: "请输入车间名称", trigger: "blur" },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  enabled: [],
  remarks: [
    { min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur" },
  ],
});

const formRef = ref(ElForm);

let formData = reactive({
  id: "",
  version: "",
  plantId: "",
  plantCode: "",
  shopFloorCode: "",
  shopFloorName: "",
  enabled: 1,
  deleted: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
});

watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      const {
        id,
        version,
        plantId,
        plantCode,
        shopFloorCode,
        shopFloorName,
        enabled,
        deleted,
        remarks,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
      } = newVal;
      Object.assign(formData, {
        id,
        version,
        plantId,
        plantCode,
        shopFloorCode,
        shopFloorName,
        enabled,
        deleted,
        remarks,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
      });
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.id = "";
  formData.version = "";
  formData.plantId = "";
  formData.plantCode = "";
  formData.shopFloorCode = "";
  formData.shopFloorName = "";
  formData.enabled = 1;
  formData.deleted = "";
  formData.remarks = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
}

const loading = ref(false);

/** 车间保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      await request({
        url: "/mdm/mdmshopfloor/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
    }
  });
}

// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});
onMounted(() => {
  getPlantList();
});
//工厂列表
const plantList = ref([]);
const getPlantList = async () => {
  const { data } = await request({
    url: "system/sysOrganization/getList",
    method: "post",
    data: { organizationType: 3 },
  });
  plantList.value = data;
};
const changePlant = (id: any) => {
  formData.plantId = id;
  formData.plantCode = plantCode(id);
};
const plantCode = (id: string) => {
  if (id) {
    const data = plantList.value.find((item) => item.id === id);
    return data.organizationCode;
  }
};
</script>
